<?php
namespace plugins\order\model;
use plugins\member\model\CommModel;
use plugins\member\model\MemberModel;
use think\Model;
use think\Db;
use plugins\goods\controller\ApiFreightPluginController;
use plugins\goods\model\GoodsSpecListModel;
use plugins\goods\model\GoodsSpecAttrModel;
use plugins\pay\lib\Pay;
use plugins\finance\model\FinanceModel;
use plugins\finance\model\FinanceAccountsModel;
class OrderModel extends Model
{
	//订单状态转换
	public function getOrderStatusChinaAttr($value,$data)
	{
		$order_status = [1=>'待付款',2=>'待发货',3=>'已发货',4=>'已完成',5=>'已关闭',6=>'已取消',7=>'售后'];
		return $order_status[$data['order_status']];
	}
	//支付方式转换
	public function getMoneyTypeChinaAttr($value,$data)
	{
		$money_type = [1=>'未支付',2=>'支付宝',3=>'微信',4=>'余额'];
		return $money_type[$data['money_type']];
	}
	//订单来源转换
	public function getOrderSourceChinaAttr($value,$data)
	{
		$order_source = [1=>'APP订单'];
		return $order_source[$data['order_source']];
	}
	//订单类型转换
	public function getOrderTypeChinaAttr($value,$data)
	{
		$order_type = [1=>'普通订单'];
		return $order_type[$data['order_type']];
	}
	//创建店铺订单,这条是带规格时使用的
	public function createOrder($post,$provice,$user)
	{
		//创建order_num
		//今日时间戳开始
		$startUnix = strtotime(date('Y-m-d'));
		//今日时间戳结束
		$endUnix = strtotime(date('Y-m-d')) + 60*60*24 ;
		//今日查询条件
		$where['submit_time'] = ['in',[$startUnix,$endUnix]];
		//今日总数
		$count = db('order')->where($where)->count();
		$count = $count + 1;
		$count = sprintf('%04d',$count);
		//流水号
		$order_num = 'order_' . date('Ymd') . $count . rand(1000,9999);		
		//-------------------------------------------------------------//
		//订单主信息
		$order = $post['order']+['order_num'=>$order_num,'submit_time'=>time()];
		$order['member_id'] = $user->uid;
		$order['remark'] = $post['remark'];
		$order_model = new OrderModel;
		$return = $order_model->allowField(true)->save($order);
		if($return){
			//总价
			$order_money = 0;
			//商品列表
			$goods = $post['goods'];
			$goods_arr = [];
			//运费
			$freight_money = 0;
			$offer_img = '';
			$offer_name = '';
			$offer_price = 0;
			$offer_num = 0;
			foreach ($goods as $key => &$value) {
				//sku搜索商品规格
				$info = ( new GoodsSpecListModel )->where(['sku'=>$value['order_goods_sku']])->find();
				if($info == null){
					continue;
				}
				$goods_arr[$key]['order_num'] = $order_num;
				$goods_arr[$key]['order_goods_img'] = $info->img ? $info->img : "";
				//搜索到的价格
				$goods_arr[$key]['order_goods_price'] = $info->price;

				//规格转换开始
				$arr = explode('#*_*#', $info->attr);
				$str = '';
				foreach ($arr as $k => $v) {
					$str .= ( new GoodsSpecAttrModel )->get(['attr_id'=>$v])->attr_name.',';
				}
				$goods_arr[$key]['order_goods_spec'] = rtrim($str,',');
				/*规格转换结束*/
				//商品数量
				$goods_arr[$key]['order_goods_num'] = $value['order_goods_num'];
				//总价递增
				$order_money += $value['order_goods_num']*$info->price;
				$goods_arr[$key] ['order_goods_sku'] = $info->sku;
				//商品id
				$goods_arr[$key]['order_goods_id'] = $info->gid;
				//查询商品信息
				$good = db('goods')->field('goods_name,freight_id,goods_img,shop_price')->where(['id'=>$info->gid])->find();

                $offer_img = zy_domain().$good['goods_img'];
                $offer_name = $good['goods_name'];
                $offer_price = $good['shop_price'];
				//商品名
				$goods_arr[$key]['order_goods_name'] = $good['goods_name'];
				//库存计算
				//减少规格库存
				$info->num = $info->num - $value['order_goods_num'];
				//减少商品总库存
				db('goods')->where(['id'=>$info->gid])->setDec('inventory',$value['order_goods_num']);
				$info->save();
			}
			//收货人信息
			$consignee = $post['consignee']+['order_num'=>$order_num];
			//运费
			$consignee['order_consignee_money'] = $freight_money;
			$consignee_model = ( new OrderConsigneeModel )->allowField(true)->save($consignee);
			//总费用计算
			$order_model->order_money = $order_money;
			$order_model->save();
			//订单商品保存
			( new OrderGoodsListModel )->allowField(true)->saveAll($goods_arr);
			//操作日志
			$log = ['order_num'=>$order_num,'log_user'=>'用户','log_type'=>'10','log_time'=>time(),'remark'=>''];
			( new OrderLogModel )->allowField(true)->save($log);

            //APP同步订单信息
            $commModel =  new CommModel();
            $member_model = new MemberModel();
            $member = $member_model->where('uid',$user->uid)->find();
            $order_param['user_id'] = $member['user_id'];
            $order_param['order_no'] = $order_num;
            $order_param['offer_img'] = $offer_img;
            $order_param['offer_name'] = $offer_name;
            $order_param['offer_price'] = $offer_price*100;
            $order_param['status'] = 1;
            $order_param['amount'] = $order_money*100;
            $order_param['gmt_create'] = date('Y-m-d H:i:s',time());
            $commModel->orderSyn($order_param);

            return ['money'=>$order_money,'order_num'=>$order_num];
		}
	}
	//订单确认
	public function confirmReceipt()
	{
		$store_finance = ( new FinanceModel )->get(['finance_type_id'=>$this->store_id,'finance_type'=>'store']);
		//店铺金额增加
		$store_finance->balance = $store_finance->balance + $this->order_money;
		$store_finance->save();
		$member_finance = ( new FinanceModel )->get(['finance_type_id'=>$this->member_id,'finance_type'=>'member']);
		if($this->money_type == 'balance'){
			$num = '302';
		}else{
			$num = '202';
		}
		//添加流水
		$data = [];
		$data['remark'] = '订单'.$this->order_num.'退款';
		$data['money'] = $this->order_money;
		$data['store'] = $store_finance->finance_id;
		$data['member'] = $member_finance->finance_id;

		( new FinanceAccountsModel )->behavior($num,$data);
	}
	//订单退款
	public function orderReturn()
	{
		$type = $this->money_type;
		//余额退款
		if($type == 'balance'){
			//应该增加回滚
			//用户金钱增加
  			$member_finance = ( new FinanceModel )->get(['finance_type'=>'member','finance_type_id'=>$this->member_id]);
  			$member_finance->balance = $member_finance->balance + $this->order_money;
  			$result1 = $member_finance->save();
  			if($result1){
	  			if($this->order_status == 4){
	  				//已完成余额订单
	  				$num = '304';
	  			}else{
	  				$num = '303';
	  			}

	  			$store_finance = ( new FinanceModel )->get(['finance_type'=>'store','finance_type_id'=>$this->store_id]);
	  			if($num == '304'){
	  				//店铺金钱减少
		  			$store_finance->balance = $member_finance->balance - $this->order_money;
		  			$result2 = $store_finance->save();
	  			}

				//订单状态更改
	  			$this->order_refund = 1;
	  			$this->order_status = 5;
	  			$this->save();

	  			$data = [];
	  			$data['remark'] = '订单'.$this->order_num.'退款';
	  			$data['money'] = $this->order_money;
	  			$data['store'] = $store_finance->finance_id;
	  			$data['member'] = $member_finance->finance_id;

	  			( new FinanceAccountsModel )->behavior($num,$data);
	  			return ['status'=>true,'message'=>'退款完成'];
  			}
  			return ['status'=>false,'message'=>'退款失败请重试'];
		}
		//判断大订单小订单
		if(strpos($this->pay_order, 'member')){
			//大订单
			$member_order = ( new OrderMemberModel )->where(['order_member_num'=>$this->pay_order])->find();
			$total_fee = $member_order->money;
		}else{
			//小订单
			$order = ( new OrderModel )->get(['order_num'=>$this->pay_order]);
			$total_fee = $order->order_money;
		}
        $wechatpay= Pay::createInstance(  $type  );	//创建pay的class
        $bizcontent = [];
        //微信
        if($type == 'wechatpay'){
	        //订单号
	        $bizcontent['out_trade_no'] = $this->pay_order;
	        //退款单号
	        $bizcontent['out_refund_no'] = uniqid();
	        //退款金额 分 暂时当前订单全部金额
	        $bizcontent['refund_fee'] = $this->order_money * 100;
	        //订单总金额
	        $bizcontent['total_fee'] = $total_fee * 100;
        }
        if($type == 'alipay'){
        	//订单号
        	$bizcontent['out_trade_no'] = $this->pay_order;
        	//退款单号
        	$bizcontent['out_request_no'] = uniqid();
        	$bizcontent['refund_amount'] = $this->order_money;
        }

  		$bizcontent = json_encode($bizcontent);
  		$res = $wechatpay->refund( $bizcontent );

  		if($res['return_code'] == 'SUCCESS'){

  			//添加流水
  			if($this->order_status == 4){
  				//已完成外部订单
  				$num = '204';
  			}else{
  				$num = '203';
  			}
  			$store_finance = ( new FinanceModel )->get(['finance_type'=>'store','finance_type_id'=>$this->store_id]);
  			$member_finance = ( new FinanceModel )->get(['finance_type'=>'member','finance_type_id'=>$this->member_id]);
  			if($num == '204'){
				//店铺金钱减少
	  			$store_finance->balance = $store_finance->balance - $this->order_money;
	  			$result2 = $store_finance->save();
  			}
  			$data = [];
  			$data['remark'] = '订单'.$this->order_num.'退款';
  			$data['money'] = $this->order_money;
  			$data['store'] = $store_finance->finance_id;
  			$data['member'] = $member_finance->finance_id;

  			( new FinanceAccountsModel )->behavior($num,$data);
  			//更改订单状态
  			$this->order_refund = 1;
  			$this->order_status = 5;
  			$this->save();
  			return ['status'=>true,'message'=>'退款完成'];
  		}
  		if($res['return_code'] == 'FAIL'){
  			return ['status'=>false,'message'=>$res['return_msg']];
  		}
	}
}